package com.zhudoo.zhilian.util.web;

import com.zhudoo.zhilian.util.IpUtil;
import com.zhudoo.zhilian.util.MapConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class UrlInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(UrlInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            //如果是OPTIONS的请求，不要打印日志
            if ("OPTIONS".equals(request.getMethod())) {
                return true;
            }
            //转换成 key value形式的Map
            Map requestParams = MapConverter.requestParameterMapToHashMap(request.getParameterMap());
            LOGGER.info("请求地址:{}，请求方式:{},请求的IP:{},参数:{}", request.getRequestURL(), request.getMethod(), IpUtil.getRemoteIp(request), requestParams);
            LOGGER.info("User-Agent:{}", request.getHeader("User-Agent"));
            String token = request.getHeader("token");
            LOGGER.info("token:{}", token);
            return true;
        } catch (Exception e) {
            LOGGER.error("请求拦截异常：{}", e);
            return false;
        }
    }
}